package fi.foyt.cs.persistence.dao.oauth;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.oauth.AuthenticatedUserCode;

public class AuthenticatedUserCodeDAO extends GenericDAO<AuthenticatedUserCode> {

  public AuthenticatedUserCode create(Long authenticatedUserId, String code) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      AuthenticatedUserCode authenticatedUserCode = new AuthenticatedUserCode();
      authenticatedUserCode.setAuthenticatedUserId(authenticatedUserId);
      authenticatedUserCode.setCode(code);
      entityManager.persist(authenticatedUserCode);
      entityManager.getTransaction().commit();
      return authenticatedUserCode;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public AuthenticatedUserCode findByAuthenticatedUserId(Long authenticatedUserId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUserCode o where authenticatedUserId = :authenticatedUserId");
    query.setParameter("authenticatedUserId", authenticatedUserId);
    return getSingleResult(query);
  } 
  
  public AuthenticatedUserCode findByCode(String code) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUserCode o where code = :code");
    query.setParameter("code", code);
    return getSingleResult(query);
  } 
  
  public AuthenticatedUserCode findByAuthenticatedUserIdAndCode(Long authenticatedUserId, String code) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUserCode o where authenticatedUserId = :authenticatedUserId and code = :code");
    query.setParameter("authenticatedUserId", authenticatedUserId);
    query.setParameter("code", code);
    return getSingleResult(query);
  }
}
